package au.org.htd.youslide;

import java.util.Date;

import javax.jdo.PersistenceManager;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public abstract class DbObject {
   PersistenceManager pm;

   @PrimaryKey
   @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
   protected Long id;

   @Persistent
   protected User creator;

   @Persistent
   protected Date lastUpdate;

   public DbObject(PersistenceManager pm) {
      this.pm = pm;
      creator = UserServiceFactory.getUserService().getCurrentUser();
      lastUpdate = new Date();
   }

   public Long getId() {
      return id;
   }

   public void setCreator(User creator) {
      this.creator = creator;
   }

   public void setLastUpdate(Date date) {
      this.lastUpdate = date;
   }

   public User getCreator() {
      return creator;
   }

   public String getCreatorName() {
      return null == creator ? "anonymous" : creator.getNickname();
   }

   public Date getLastUpdate() {
      return lastUpdate;
   }

   public PersistenceManager getPm() {
      return pm;
   }

   public void setPm(PersistenceManager pm) {
      this.pm = pm;
   }

   @SuppressWarnings("unchecked")
   public <T> T save() {
      return (T) pm.makePersistent(this);
   }

   public void delete() {
      pm.deletePersistent(this);
   }

   public void closeConnection() {
      pm.close();
   }

   public abstract DbObject get(Long id);
}
